<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">管理员登录</h2>
      <el-form ref="formRef" @keyup.enter="handleLogin">
        <el-form-item>
          <el-input v-model="loginForm.username" placeholder="请输入管理员用户名" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="loginForm.admin_password" placeholder="请输入管理员密码"/>
        </el-form-item>
        <el-form-item>
          <el-input v-model="loginForm.game" placeholder="请输入game" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="text" @click="goUserLogin" style="width: 100%">
            切换到普通用户登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const loginForm = reactive({
  username: '',
  admin_password: '',
  game: ''
})

const loading = ref(false)

const handleLogin = async () => {
  if (!loginForm.username || !loginForm.admin_password || !loginForm.game) {
    ElMessage.warning('请填写完整信息')
    return
  }
  try {
    loading.value = true
    const response = await axios.post('http://127.0.0.1:8000/backend/admin_login/', {
      username: loginForm.username,
      admin_password: loginForm.admin_password,
      game: loginForm.game,
      login_type: 'admin'
    })
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg)
      // 存储管理员信息
      localStorage.setItem('phone', loginForm.username)
      // 你可以加一个role字段区分
      localStorage.setItem('role', 'admin')
      router.push('/')
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('登录失败，请检查输入')
  } finally {
    loading.value = false
  }
}


const goUserLogin = () => {
  router.push('/login')
}
</script>